from enum import Enum
import csv

class Gender(Enum):
    MALE = '男'
    FEMALE = '女'

def calculate_bmr(gender, weight, height, age):
    # 这里使用哈里斯-贝内迪克特公式计算BMR
    if gender == Gender.MALE:
        return 88.362 + (13.397 * weight) + (4.799 * height) - (5.677 * age)
    else:
        return 447.593 + (9.247 * weight) + (3.098 * height) - (4.330 * age)

def get_valid_input(prompt, cast_to_type, min_value=None, max_value=None):
    while True:
        try:
            value = cast_to_type(input(prompt).strip())
            if min_value is not None and value < min_value:
                print(f"输入值必须大于或等于{min_value}。")
                continue
            if max_value is not None and value > max_value:
                print(f"输入值必须小于或等于{max_value}。")
                continue
            return value
        except ValueError:
            print(f"输入必须是{cast_to_type.__name__}类型。")

def validate_input(value, min_value, max_value):
    if value < min_value or value > max_value:
        print(f"输入值必须在{min_value}和{max_value}之间。")
        return False
    return True

def write_to_csv(data, filename='bmr_data.csv'):
    with open(filename, mode='a', newline='') as file:
        writer = csv.writer(file)
        # 写入标题行（如果文件是新创建的）
        if file.tell() == 0:
            writer.writerow(['性别', '体重(kg)', '身高(cm)', '年龄', 'BMR'])
        # 写入数据行
        writer.writerow(data)

def main():
    while True:
        gender_input = input("请输入性别（男/女）或输入'退出'来结束程序: ").strip().lower()
        if gender_input == '退出':
            print("程序已退出。")
            break

        # 根据用户输入获取Gender枚举类型的值
        if gender_input == '男':
            gender = Gender.MALE
        elif gender_input == '女':
            gender = Gender.FEMALE
        else:
            print("输入无效，请重新输入。")
            continue

        height = get_valid_input("请输入身高（厘米）: ", float, 0, 250)
        age = get_valid_input("请输入年龄: ", int, 1, 120)  # 年龄通常从1岁开始
        weight = get_valid_input("请输入体重（千克）: ", float)

        bmr = calculate_bmr(gender, weight, height, age)
        print(f"你的BMR指数是：{bmr:.2f} 卡路里每天")

        # 准备要写入的数据
        csv_data = [gender.value, weight, height, age, bmr]
        # 将结果写入到CSV文件
        write_to_csv(csv_data)

if __name__ == "__main__":
    main()